package com.onlineclass.teacherserver.controller;


import com.onlineclass.teacherserver.service.IVideoService;
import com.onlineclassbackstage.beans.ResultObject;
import com.onlineclassbackstage.beans.Video;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.util.UUID;

@RestController
@Slf4j
public class VideoController {

    @Value("${file.uploadFolder}")
    private String uploadPath; //文件上传的地址

    @Value("${videourl}")
    private String videourl;

    @Autowired
    IVideoService service;

    @RequestMapping("/uploadVideo")
    public ResultObject uploadVideo(MultipartFile file, HttpServletRequest request, Video video) {
        //上传目录地址
        String uploadDir = uploadPath;
        //如果目录不存在，自动创建文件夹
        File dir = new File(uploadDir);
        if (!dir.exists()) {
            dir.mkdir();
            log.info("创建文件：" + uploadDir);
        }
        String suffix = null;
        String fileName = null;
        try {

            if (file != null) {
                log.info("开始上传文件.......");
                //调用上传方法
                suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); //后缀名
                fileName = UUID.randomUUID() + suffix;
                IOUtils.copy(file.getInputStream(), new FileOutputStream(uploadDir + "\\" + fileName));
                //file[i].transferTo(new File(uploadDir+"\\"+fileName));
                video.setVideourl(videourl+fileName);
                ResultObject resultObject = service.insertVideo(video);
                log.info("上传" + uploadDir + "\\" + fileName + "文件成功！");
                return resultObject;
            }
            log.info("上传结束！所有文件上传文件至：" + uploadDir);
            return null;
        } catch (Exception e) {
            //打印错误堆栈信息
            e.printStackTrace();
            log.info("上传文件失败！");
            return new ResultObject(0,"上传失败","");

        }
    }



}
